<?php
/**
 * Created by PhpStorm.
 * User: Bostin
 * Date: 2019-02-15
 * Time: 10:13
 */

namespace Bostin\Translator\Sdk;


use GuzzleHttp\Client;

/**
 * Class Youdao
 * @package Bostin\Translator\Sdk
 */
class Youdao
{
    /**
     * @var string
     */
    protected $api = 'https://openapi.youdao.com/openapi';

    /**
     * @var
     */
    protected $client;

    /**
     * @var string
     */
    protected $appKey;

    /**
     * @var string
     */
    protected $secret;

    /**
     * @var array
     */
    protected $config;

    /**
     * Youdao constructor.
     * @param string $appKey
     * @param string $secret
     * @param array $config
     */
    public function __construct(string $appKey, string $secret, array $config = [])
    {
        $this->appKey = $appKey;
        $this->secret = $secret;
        $this->config = $config;
    }

    /**
     * @return Client
     */
    private function getClient(): Client
    {
        if (is_null($this->client)) {
            $this->client = new Client($this->config['guzzle'] ?? []);
        }
        return $this->client;
    }

    /**
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function textTranslate(string $sourceText, string $source, string $target): ?string
    {
        $result = $this->request(['q' => $sourceText, 'from' => $source, 'to' => $target]);
        return $result['translation'][0] ?? null;
    }

    /**
     * @param string $sourceText
     * @param int $salt
     * @return string
     */
    private function sign(string $sourceText, int $salt): string
    {
        return strtolower(md5($this->appKey . $sourceText . $salt . $this->secret));
    }

    /**
     * @param array $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request(array $params): array
    {
        $salt = rand(100000, 9999999);

        $params = [
            'q' => $params['q'] ?? '',
            'from' => $params['from'] ?? 'auto',
            'to' => $params['to'] ?? 'en',
            'appKey' => $this->appKey,
            'salt' => $salt,
            'sign' => $this->sign($params['q'] ?? '', $salt),
        ];

        $body = (string) $this->getClient()->request('POST', $this->api, ['form_params' => $params])->getBody();
        return json_decode($body, true);
    }
}